import { onMounted, Ref } from 'vue';
import { ElMessage } from 'element-plus';

// 默认属性
const defaultState: BasicTableProps = {
	// 页面数据加载loading
	loading: false,
	// 条件查询参数
	queryParams: {},
	// table数据列表
	tableData: [],
	// table选中数据
	tableSelectionRows: [],
	// 分页组件属性配置
	pagination: {
		current: 1,
		size: 10,
		total: 0,
		pageSizes: [10, 30, 50, 100, 300],
		layout: '->, total, prev, pager, next, sizes, jumper',
	} as Pagination,
};

/**
 * 合并默认属性配置和自定义属性配置
 * @param options 默认属性配置对象
 * @param props 自定义属性配置对象
 * @returns 合并后的属性配置对象
 */
const mergeDefaultOptions = (options: any, props: any): BasicTableProps => {
	for (const key in options) {
		if (!Object.getOwnPropertyDescriptor(props, key)) {
			props[key] = options[key];
		}
	}
	return props;
};

// 对外开放通用函数
export function useTable(requestApi: any, queryFormRef: Ref, options: BasicTableProps) {
	// 覆盖默认值
	const state = mergeDefaultOptions(defaultState, options);

	// 生命周期
	onMounted(() => {
		getTableData();
	});

	/**
	 * 获取表格数据
	 */
	const getTableData = async () => {
		if (requestApi) {
			try {
				state.loading = true;
				const res = await requestApi().list({
					...state.queryParams,
					current: state.pagination?.current,
					size: state.pagination?.size,
				});
				state.tableData = res.data.records;
				state.pagination!.total = res.data.total;
			} catch (e: any) {
				// 捕获异常并显示错误提示
				console.error('获取表格数据时捕获到异常：', e);
				ElMessage.error('获取表格数据时捕获到异常：' + (e.msg || e.message || e.data.msg));
			} finally {
				// 结束加载数据，设置state.loading为false
				state.loading = false;
			}
		}
	};

	// table多选事件
	const handleSelectionChange = (val: any) => {
		state.tableSelectionRows = val;
		console.log('当前选择内容：', state.tableSelectionRows);
	};

	// 分页改变事件
	const handlePaginationChange = (currentPage: number, pageSize: number) => {
		state.pagination!.size = pageSize;
		state.pagination!.current = currentPage;
		getTableData();
	};

	// 删除用户
	const handleDelete = async (ids: object) => {
		if (requestApi) {
			try {
				const res = await requestApi().del(ids);
				if (res.code == 200) {
					ElMessage.success('删除成功');
					getTableData();
				}
			} catch (err: any) {
				console.log('删除用户时捕获到异常', err);
				// 捕获异常并显示错误提示
				ElMessage.error(err.msg || err.data.msg);
			}
		}
	};

	// 清空搜索条件
	const resetQuery = () => {
		queryFormRef.value?.resetFields();
		getTableData();
	};

	return {
		getTableData,
		handleSelectionChange,
		handlePaginationChange,
		handleDelete,
		resetQuery,
	};
}
